package com.haois.ws.web.module.rbac.rest;


import com.haois.component.common.enu.JwtEnum;
import com.haois.component.security.HandleCookie;
import com.haois.component.security.HandleToken;
import com.haois.component.security.ProduceJwt;
import com.haois.ws.web.module.rbac.daoman.Manager;
import com.haois.ws.common.util.MD5Coder;
import com.haois.ws.common.constant.NetworkUtil;
import com.haois.ws.common.constant.StatusCode;
import com.haois.ws.common.constant.daomain.Subject;
import com.haois.ws.web.module.rbac.service.ManagerService;

import com.haois.ws.common.constant.Reply;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created by RuiHaoZ on 2017/3/11.
 */
@RestController
@RequestMapping("/api/web/log")
public class ManagerLogController {
    @Autowired
    private ManagerService managerService;

    private HandleToken handleToken = new HandleToken();
    private ProduceJwt produceJwt = new ProduceJwt();

    private Logger logger = LoggerFactory.getLogger(ManagerLogController.class);

    @Autowired
    private RedisTemplate<String, Object> template;


    /**
     * @api {POST} /api/web/log/login  登录
     * @apiGroup webManagerLogin
     * @apiName Login
     * @apiDescription 组织管理员登录
     * @apiParam {String} account 账号
     * @apiParam {String} password 密码
     * @apiParamExample {json} 请求样例：
     * POST /api/web/log/login
     * {
     * "account":"test"
     * "password": "test"
     * }
     * @apiSuccessExample {json} 返回样例:
     * {
     * "code":0,"msg":"登录成功"
     * }
     */

    @RequestMapping(value = "/login", method = RequestMethod.POST, params = {"account", "password"})
    public String accountCheck(String account, String password,
                               HttpServletResponse response, HttpServletRequest request) {
        Manager manager = managerService.getByAccount(account);
        Reply reply = null;
        if (manager != null) {
            String md5Password = MD5Coder.encodeCombine(account, password);
            if (manager.getPassword().equals(md5Password)) {

                template.opsForValue().set(manager.getAccount(), manager,2, TimeUnit.HOURS);
                template.opsForList().leftPush("Login-Manager",manager);

                long nowMillis = System.currentTimeMillis();
                Date nowTime = new Date(nowMillis);

                String subject = handleToken.generalSubject(new Subject(manager));
                String jwt = produceJwt.produceToken(subject, nowTime, JwtEnum.WEB);
                HandleCookie.saveCookie(response, StatusCode.COOKIE_JWT_WEB, jwt);
                managerService.updateLogin(manager.getId(), nowTime);

                logger.info("管理员[{}]登录成功,IP地址为[{}]", account, NetworkUtil.getIpAddress(request));
                reply = new Reply("00", "登录成功");
            } else {
                logger.info("管理员[{}]登录失败,密码错误", account);
                HandleCookie.deleteCookie(response, StatusCode.COOKIE_JWT_WEB);
                reply = new Reply("10", "登录失败");
            }
        } else {
            logger.info("用户[{}]登录失败,账号不存在", account);
            HandleCookie.deleteCookie(response, StatusCode.COOKIE_JWT_WEB);
            reply = new Reply("10", "登录失败");
        }
        return reply.toJson();
    }

    /**
     * @api {GET} /api/web/log/logout  退出登录
     * @apiGroup webManagerLogin
     * @apiName Logout
     * @apiDescription 组织管理员退出登录
     * @apiSuccessExample {json} 返回样例:
     * {
     * "code":0,"msg":"登出成功"
     * }
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String accountOut(HttpServletResponse response, HttpServletRequest request) {
        String token = HandleCookie.getValueByName(request, StatusCode.COOKIE_JWT_WEB);
        String mid = handleToken.getValueByKey(token, StatusCode.SUBJECT_KEY_NUM);
        HandleCookie.deleteCookie(response, StatusCode.COOKIE_JWT_WEB);
        logger.info("编号为[{}]的管理员,退出成功", mid);
        return new Reply("00", "退出成功").toJson();
    }

    /**
     * @api {GET} /api/app/log/logState  检查Web登录状态
     * @apiGroup webManagerLogin
     * @apiName checkState
     * @apiDescription 检测是否登录
     * @apiSuccessExample {json} 返回样例:
     * {
     * "00":"已登录",
     * "10":"未登录"
     * }
     */
    @RequestMapping(value = "/logState", method = RequestMethod.GET)
    public String check(HttpServletRequest request) {
        try {
            HandleToken handleJWT = new HandleToken();
            String token = HandleCookie.getValueByName(request, StatusCode.COOKIE_JWT_WEB);
            handleJWT.analyzeJWT(token);
            String account = handleJWT.getValueByKey(token, StatusCode.SUBJECT_KEY_NUM);
            Date date = handleJWT.getIssuedAt(token);
            Manager manager = managerService.getByAccount(account);
            if (date.compareTo(manager.getLoginTime()) != 0) {
//                throw new ErrorException(ReturnState.CODE_13, "该用户已在其他地方登录过，请重新登录");
            }
            return new Reply("00", "已登录").toJson();
        } catch (Exception e) {
            String msg = StringUtils.isBlank(e.getMessage()) ? "当前用户信息不存在，请重新登录!!" : e.getMessage();

            return new Reply("10", msg).toJson();
        }


    }
}
